package com.example.cloud.filter;

import com.example.cloud.constants.CommonConstants;
import com.example.cloud.utils.JwtHelper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by wangtao on 2018/1/30.
 */
public class RequestFilter extends ZuulFilter {
    private static final Logger logger = LoggerFactory.getLogger(RequestFilter.class);
    @Value("${spring.application.name}")
    private String name;
    @Value("${client.secret}")
    private String secret;
    @Autowired
    private JwtHelper jwtHelper;
    @Override
    public String filterType() {
        // 返回使用的过滤器类型
        return "pre";
    }

    @Override
    public int filterOrder() {
        // 决定过滤器执行顺序，不同过滤器可返回相同值
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 是否启用过滤器
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String requestURI = request.getRequestURI();
        String url = "";
        if(requestURI.contains("/auth")){
            url = request.getRequestURI().substring("/auth".length());
        }else if(requestURI.contains("/user")){
            url = request.getRequestURI().substring("/user".length());
        }
        if(url.startsWith("/login") || url.startsWith("/getToken")
                || url.startsWith("/print") || url.startsWith("/socket")
                || url.startsWith("/skin/type") || url.startsWith("/searchPatient")){
            return null;
        }
        // 校验access-token是否合法
        String token = request.getHeader("access_token");
        try {
            jwtHelper.getUserByToken(token);
        } catch (IllegalArgumentException e) {
            // *** 过滤该请求，不对其路由
            ctx.setSendZuulResponse(false);
            ctx.set("error.status_code", CommonConstants.EX_TOKEN_EMPTY_CODE);
//            ctx.set("error.exception", e);
            ctx.set("error.message", "access-token不能为空!");
            return null;
        } catch (ExpiredJwtException e) {
            ctx.setSendZuulResponse(false);
            ctx.set("error.status_code", CommonConstants.EX_TOKEN_EXPIRED_CODE);
            ctx.set("error.message", "access-token已过期!");
            return null;
        } catch (Exception e) {
            ctx.setSendZuulResponse(false);
            ctx.set("error.status_code", CommonConstants.EX_TOKEN_ILLEGAL_CODE);
            ctx.set("error.message", "access-token无效!");
            return null;
        }
        return null;
    }
}
